# -*- coding: utf-8 -*-
import os
import logging
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from apps import base_path
from django.utils import simplejson
from datetime import datetime
from apps.chart.openflash.utils import handleRequestURL
from code import interact


class ChartOpenFlash(webapp.RequestHandler):
    def get(self):
        path = os.path.join(base_path, "templates/chart/openflash/chart.html")
        form = self.request.GET
        others, jsonObj = self.getJsonData(form)
        data = {"json_data": jsonObj, "width": others.setdefault("width", 500), "height": others.setdefault("height", 300)}
        t = template.render(path, data)
        self.response.out.write(t)

    def getJsonData(self, form):
        data_list = map(int, form.get("datas").split(","))
        request_url = handleRequestURL(form.keys(), self.request.query_string)
        data_list = request_url['datas']
        logging.info('request_url: %s' % request_url )
        tp = request_url.setdefault("type", "line")
        elements = [{"type": tp, "values": data_list}]
        title = {"text": str(datetime.now())}
        jsonObj = simplejson.dumps({"elements": elements,"title":{"text":"Sun Dec 27 2009"}})
        return request_url, jsonObj


# for test
class TestChartOpenFlash(webapp.RequestHandler):
    def _handleOpenFlash(self):
        path = os.path.join(base_path, "templates/chart/openflash/test_chart.html")
        data = {"json_data": self.getJsonData()}
        t = template.render(path, data)
        self.response.out.write(t)

    def getJsonData(self):
        data_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
        elements = [{"type": "bar_ground_glass", "values": data_list}]
        title = {"text": str(datetime.now())}
        jsonObj = simplejson.dumps({"elements":[{"type":"bar_round_glass","values":[9,8,7,6,5,4,3,2,1]}],"title":{"text":"Sun Dec 27 2009"}})
        return jsonObj
        
    
    def _handleJson(self):
        data_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
        elements = [{"type": "bar_ground_glass", "values": data_list}]
        title = {"text": str(datetime.now())}
        jsonObj = simplejson.dumps({"elements":[{"type":"bar_round_glass","values":[9,8,7,6,5,4,3,2,1]}],"title":{"text":"Sun Dec 27 2009"}})
        self.response.headers['Content-Type'] = "text/plain"
        self.response.out.write(jsonObj)
        
    def get(self):
        if self.request.path.endswith("/chart/openflash/json/"):
            self._handleJson()
        elif self.request.path.endswith("/chart/openflash/"):
            self._handleOpenFlash()

